AWS DynamoDB with CLI : update and delete query
Amazon's DynamoDB is a NoSQL key-value store offering from AWS which is quite popular among its users. Using DynamoDB has a lot of advantages and there are various ways of performing CRUD operations on it, in this article I would like to walk you through creating some DynamoDB tables, inserting data in these tables and various ways of reading this data.
Previously I wrote a blog in which I explained how to create the tables, write to them and read data from them. I will be using the same data which I inserted last time for this demo. To read that blog go here.
Updating Data
Let's update some data first, this time I will be focusing on the Forum table and update one of its items.
This is the state of Forum before updating it.
I would like to update the item with Name : Amazon S3 , Name is the partition key for the Forum table. Furthermore I would like to add an attribute Views to the targeted item, in which case the query is:
aws dynamodb update-item \ --table-name Forum \ --key '{"Name" : {"S" : "Amazon S3"}}' \ --update-expression "SET Messages=:messages" \ --condition-expression "Category=:category" \ --expression-attribute-values '{":messages" : {"N": "10" }, ":category" : {"S" : "Amazon Web Services"}}' \ --return-consumed-capacity TOTAL
This is how the table looks after the update.
In an update query, we use placeholders for the values which we need to perform actions with, in the update query as you can see, I have used :messages for messages and :category as a placeholders and later used the --expression-attribute-values option to define the values of the placeholders.
Deleting Data
For this I would like to try another table, hence I will be using the Product Catalog table which has Id as its partition key. If you do not know the schema of your table then you can run the decribe-table command. Here's an example :
aws dynamodb describe-table \ --table-name ProductCatalog
Now that we know the table schema, we can proceed with the deletion of the item.
aws dynamodb delete-item \ --table-name ProductCatalog \ --key '{"Id" : {"N" : "205"}}' \ --return-consumed-capacity TOTAL
As you can see, after running the delete command I ran a get-item command to confirm if the item I wanted to delete from the table has been actually deleted or not, however this also consumes RCUs so be aware of using it.
Conclusion
Along with the previous blog, this now completes a comprehensive demo of performing CRUD operations on DynamoDB. I hope this has made your understanding better.